﻿using System;
using System.IO;
using PathFind;
using UnityEditor;
using UnityEngine;

namespace PathFindEditor {
    public static class MapLoader
    {
        [MenuItem("Paths/Save to file", true)]
        public static bool CanSave()
        {
            return Application.isPlaying;
        }

        [MenuItem("Paths/Save to file")]
        public static void SaveToFile() {
            if (!Application.isPlaying) {
                EditorUtility.DisplayDialog("文件", "该文件不存在", "确定");
                return;
            }
            var startPath = EnsureStartPath();
            try {
                var path = EditorUtility.SaveFilePanel("Save to Graphs", startPath,
                    "mapdata1","bytes");
                var obj = GameObject.Find("Canvas/SquireEdit");
                var edit = obj.GetComponent<SquireEdit>();
                edit.WriteAlgoToFile(path);
                Debug.Log($"path:{path}");
            }
            catch (ArgumentException e) {
                Debug.Log(e.Message);
            }
        }

        private static string EnsureStartPath() {
            var startPath = Path.Combine(Application.dataPath, "MapDatas");
            if (!Directory.Exists(startPath)) {
                Directory.CreateDirectory(startPath);
            }

            return startPath;
        }

        [MenuItem("Paths/Load from file", true)]
        public static bool CanLoad()
        {
            return Application.isPlaying;
        }

        [MenuItem("Paths/Load from file")]
        public static void LoadFromFile() {
            var startPath = EnsureStartPath();
            try {
                var obj = GameObject.Find("Canvas/SquireEdit");
                var edit = obj.GetComponent<SquireEdit>();
                string path = EditorUtility.OpenFilePanel("Load from File", startPath, "bytes");
                edit.ReadAlgoFromFile(path);
                Debug.Log($"path:{path}"); 
            }
            catch (ArgumentException e) {
                Debug.Log(e.Message);
            }
        }
    }
}
